//登录和注册需要的User类
var User = require('../models/user');
//提问需要的Post类
var Post = require('../models/post');
//回答需要的Answer类
var Answer = require('../models/answer');
//头像上传需要的upload类
var upload = require('../models/upload');
//引入头像上传需要的multer插件
var multer = require('multer');
//需要引入一个加密的模块
var crypto = require('crypto');


//权限问题
//如果已经登录 不能重复登录
function checkLogin(req, res, next) {
    if (!req.session.user) {
        req.flash('error', '您还没有登录!');
        res.redirect('/login');
    }
    next();
}
//如果登录不能访问访问登录和注册页面的
function checkNotLogin(req, res, next) {
    if (req.session.user) {
        req.flash('error', '已登录!');
        res.redirect('back');//返回之前的页面
    }
    next();
}
module.exports = function (app) {
    //首页
    app.get('/', function (req, res) {
        var page = parseInt(req.query.p) || 1;
        console.log(page);
        Post.getTen(null, page, function (err, asks, total) {
            if (err) {
                asks = [];
            }
            res.render('index', {
                title: '主页',
                total: total,
                user: req.session.user,
                asks: asks,
                page: page,
                //判断是否是第一页
                isFirstPage: (page - 1) == 0,
                //判断是否是最后一页
                isLastPage: (page - 1) * 10 + asks.length == total,
                success: req.flash('success').toString(),
                error: req.flash('error').toString()
            })
        })
    });
    //注册页面
    app.get('/reg', checkNotLogin, function (req, res) {
        res.render('reg', {
            title: '注册',
            user: req.session.user,
            success: req.flash('success').toString(),
            error: req.flash('error').toString()
        })

    });
    //注册行为
    app.post('/reg', function (req, res) {
        var name = req.body.name;
        var password = req.body.password;
        var repeatPsd = req.body['password-repeat'];
        var email = req.body.email;
        //看下重复密码是否等于密码
        if (repeatPsd != password) {
            req.flash('error', '两次输入的密码不一致!')
            return res.redirect('/reg');
        }
        //对密码进行加密处理
        var md5 = crypto.createHash('md5');
        var password = md5.update(req.body.password).digest('hex');
        var newUser = new User({
            name: name,
            password: password,
            email: email

        });
        //检查用户名是否存在
        User.get(newUser.name, function (err, user) {
            //如果发生了错误,跳转回首页
            if (err) {
                req.flash('error', err);
                return res.redirect('/');
            }
            //如果存在重复的用户名
            if (user) {
                req.flash('error', '用户名已经存在');
                return res.redirect('/reg');
            }
            //正确情况下
            newUser.save(function (err, user) {
                if (err) {
                    req.flash('error', err);
                }
                //用户信息存入session
                req.flash('success', '注册成功');
                res.redirect('/login');
            })
        })
    });

    //登录
    app.get('/login', checkNotLogin, function (req, res) {
        res.render('login', {
            title: '登录',
            user: req.session.user,
            success: req.flash('success').toString(),
            error: req.flash('error').toString()
        })
    })
    //登录行为
    app.post('/login', function (req, res) {
        //1.检查下用户名有没有
        //2.检查下密码对不对
        //3.存储到session中用户的登录信息
        //4.跳转到首页
        var md5 = crypto.createHash('md5');
        var password = md5.update(req.body.password).digest('hex');
        User.get(req.body.name, function (err, user) {
            if (!user) {
                //说明用户名不存在
                req.flash('error', '用户名不存在');
                return res.redirect('/login');
            }
            //检查两次密码是否一样
            if (user.password != password) {
                req.flash('error', '密码错误');
                return res.redirect('/login');
            }
            req.session.user = user;
            req.flash('success', '登录成功');
            res.redirect('/');
        })

    });
    //个人信息页面
    app.get('/userInfo', checkLogin, function (req, res) {
        res.render('userInfo', {
            title: '个人资料',
            user: req.session.user,
            success: req.flash('success').toString(),
            error: req.flash('error').toString(),
            photo: 'uploads/' + req.session.user.picUrl,
        })
    });
    //个人信息操作
    app.post('/userInfo', upload.single("photo"), function (req, res) {
        if (req.picUrl) {
            User.update(req.session.user.name, req.picUrl, req.body.sign, function (err, user) {
                if (err) {
                    req.flash('err', '头像上传失败!');
                    res.redirect('/userInfo');
                }
                req.session.user = user;
                //头像上传成功后对post集合进行更新
                Post.updatePhoto(req.session.user.name, req.picUrl, function (err) {
                    if (err) {
                        console.log('个人资料发布失败!');
                    } else {
                        req.flash('success', '个人资料发布成功!');
                        res.redirect('/');
                    }
                })

            });
        } else {
            res.end("请选择图片后上传");
        }
    });
    //提问页面
    app.get('/ask', checkLogin, function (req, res) {
        res.render('ask', {
            title: '提问',
            photo: '/uploads/' + req.session.user.picUrl,
            success: req.flash('success').toString(),
            error: req.flash('error').toString()
        })
    })
    //提问行为
    app.post('/ask', function (req, res) {

        var currentUser = req.session.user;
        var ask = new Post(currentUser.name, req.body.askTitle, req.body.askContent, req.session.user.picUrl);
        ask.save(function (err) {
            if (err) {
                req.flash('error', '保存提问出错!');
                return res.redirect('/');
            }
            req.flash('success', '提问成功!');
            res.redirect('/');
        })
    });

    //问题详情
    app.get('/u/:name/:second/:askTitle', function (req, res) {
        Post.getOne(req.params.name, req.params.second, req.params.askTitle, function (err, ask) {
            if (err) {
                req.flash('error', '找不到此提问');
                return res.redirect('/');
            }
            //console.log(ask);
            res.render('askDetail', {
                title: '提问详情',
                user: req.session.user,
                ask: ask,
                success: req.flash('success').toString(),
                error: req.flash('error').toString()
            })
        })
    });

    //问题的回答
    app.post('/answer/:name/:second/:askTitle', checkLogin, function (req, res) {
        var date = new Date();
        var time = date.getFullYear() + '-' +
            (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' +
            (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ":" +
            (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
        var answer = {
            name: req.body.name,
            time: time,
            content: req.body.content
        };

        var newAnswer = new Answer(req.params.name, req.params.second, req.params.askTitle, answer);
        newAnswer.save(function (err) {
            if (err) {
                req.flash('error', '保存回复的时候出错了！');
                return res.redirect('back')
            }
            req.flash('success', '回复成功！');
            res.redirect('back');
        })
    });
    //提问编辑页面
    app.get('/askEdit/:name/:second/:askTitle', checkLogin, function (req, res) {
        var currentUser = req.session.user;
        Post.askEdit(currentUser.name, req.params.second, req.params.askTitle, function (err, ask) {
            if (err) {
                req.flash('error', '未找到相应的文章！')
                return res.redirect('back')
            }
            res.render('askEdit', {
                title: '提问编辑',
                user: req.session.user,
                ask: ask,
                success: req.flash('success').toString(),
                error: req.flash('error').toString()
            })
        });

    });
    //提问编辑行为
    app.post('/askEdit/:name/:second/:askTitle', function (req, res) {
        Post.update(req.params.name, req.params.second, req.params.askTitle, req.body.askContent, function (err) {
            var url = encodeURI('/u/' + req.params.name + '/' + req.params.second + '/' + req.params.askTitle);
            if (err) {
                req.flash('error', '提问编辑失败！');
                return res.redirect(url);
            }
            req.flash('success', '提问编辑成功!');
            //编辑成功后跳转到提问详情页面
            res.redirect(url);
        })
    });
    //提问删除行为
    app.get('/askDelete/:name/:second/:askTitle', checkLogin, function (req, res) {
        Post.askDelete(req.params.name, req.params.second, req.params.askTitle, function (err) {
            if (err) {
                req.flash('error', err);
                return res.redirect('back')
            }
            req.flash('success', '删除成功');
            //删除成功后跳转到提问详情页面
            res.redirect('/');
        })
    });

    //通过文章的标题对文章进行搜索
    app.get('/askSearch', function (req, res) {
        Post.search(req.query.keyword, function (err, asks) {
            if (err) {
                req.flash('error', err);
                return res.redirect('/');
            }
            res.render('askSearch', {
                title: '搜索',
                asks: asks,
                user: req.session.user,
                success: req.flash('success').toString(),
                error: req.flash('error').toString()
            })
        })
    });

    //退出
    app.get('/logout', function (req, res) {
        req.session.user = null;
        req.flash('success', '成功退出');
        res.redirect('/');
    });

};













